<template>
  <view>
    <Header type="back" title="优惠券选择" />
    <view class="w-100" :class="'h' + bar_height"></view>

    <view
      class="w-100 h1356 bg-f8ff ty-use re"
      :style="'height:' + (height * 1 + 80) + 'rpx'"
    >
      <view class="px-2-6">
        <view class="px-2-4 border-bottom py-3 font28 t-20"> 可用优惠券 </view>
      </view>
      <scroll-view class="scroll-view_H uni-scroll top125" scroll-y="true">
        <view class="w-100 px-2-6">
          <view
            class="w-100 h222 f-b-c circle34 show0 mb-3 bg-f8ff re"
            v-for="(item, index) in coupon_list"
            :key="item.id"
            @click="elsect_coupon(item)"
          >
            <view class="w226 h222 ty-circle-img f-c-c bg-theme_5">
              <view
                class="f-c-b h80 t-20"
                style="display: flex; align-items: center"
              >
                <text
                  class="font700 f-c-c h70 mr-05"
                  :class="item.type === 1 ? setnss(item) : 'font88'"
                  >{{ item.type === 1 ? item.couponFee : item.rebate }}</text
                >{{ item.type === 1 ? "元" : "折" }}
              </view>
            </view>
            <view
              class="w470 bg-white h222 fs-b-b pl-4 pr-2 py-3 ty-circle-box re"
            >
              <view>
                <view class="font32 t-20 font600 h32"
                  ><text class="text-red mr-1"
                    >[{{ coupon_type[item.orderType] }}]</text
                  >
                  {{ item.name || "" }}</view
                >
                <view class="font24 t-8 pt-1">{{ item.notice || "" }}</view>
              </view>
              <view class="w-100">
                <view class="font24 t-8"
                  >到期时间:{{ item.expiredTime || "" }}</view
                >
              </view>

              <image
                src="../../static/icon_select_cur.png"
                v-if="item.id == coupon_code"
                class="ab bottom30 z-99 w42 h42 right30"
              />
            </view>
            <view class="ab left206 top0 bottom0">
              <view
                class="w12 h12 show0-in ab left14 top28 bg-f8ff rounded-circle"
              ></view>
              <view
                class="w12 h12 show0-in ab left14 top50 bg-f8ff rounded-circle"
              ></view>
              <view
                class="w12 h12 show0-in ab left14 top72 bg-f8ff rounded-circle"
              ></view>
              <view
                class="w12 h12 show0-in ab left14 top94 bg-f8ff rounded-circle"
              ></view>
              <view
                class="w12 h12 show0-in ab left14 top116 bg-f8ff rounded-circle"
              ></view>
              <view
                class="w12 h12 show0-in ab left14 top138 bg-f8ff rounded-circle"
              ></view>
              <view
                class="w12 h12 show0-in ab left14 top160 bg-f8ff rounded-circle"
              ></view>
              <view
                class="w12 h12 show0-in ab left14 top182 bg-f8ff rounded-circle"
              ></view>
              <view
                class="ab left0 w40 h40 bg-f8ff show-in-bottom"
                style="top: -20rpx"
              ></view>
              <view
                class="ab left0 w40 h40 bg-f8ff show-in-top"
                style="bottom: -20rpx"
              ></view>
            </view>
          </view>
        </view>
        <view class="w-100 h180"></view>
        <view
          class="w-100 t-a font24 t-3 pt-12 pb-1"
          v-if="coupon_list.length == 0"
          >暂无优惠券</view
        >
      </scroll-view>
    </view>
  </view>
</template>

<script>
import Header from "../../components/header.vue";

import { my_coupon } from "../../api/coupon.js";

export default {
  components: {
    Header,
  },
  data() {
    return {
      goods: [],
      height: 0,
      bar_height: 0,
      coupon_list: [],
      coupon_code: 0,
      query: {
        currentPage: 1,
        pageSize: 412,
        status: 1,
        orderType: "",
      },
      coupon_type: {
        TICKET: "票务",
        ACTIVITY: "活动",
        YEAR_CARD: "年卡",
        MALL: "商城",
        FOOD: "餐饮",
        // MAP:'地图',
        LINE: "路线",
        WORKSHOP: "工坊",
      },
      money: 0,
    };
  },

  onLoad(val) {
    this.goods = JSON.parse(val.goods);
    console.log(this.goods, "商品列表------------------------");
    //获取商品列表 筛选可用优惠券列表
    this.money = val.money || 0;
    this.query.orderType = val.type;
    this.get_coupon();
  },
  created() {
    this.bar_height = uni.getStorageSync("toprpx"); //顶部高度
    this.height = uni.getStorageSync("map_height"); //其他页面使用的高度
  },
  mounted() {
    let coupon_code = uni.getStorageSync("change_coupon") || {};
    this.coupon_code = coupon_code.id || 0;
  },
  methods: {
    setnss(item) {
      let xd = "font40";
      if (item.couponFee < 1000) {
        xd = "font88";
        if (item.type == 1 && item.couponFee.toString().length > 4) {
          xd = "font45";
        }
      }
      return xd;
    },
    elsect_coupon(val) {
      this.coupon_code = val.id;
      // type 1 满减 折扣
      if (val.type === 1) {
        // 满减金额直接赋值
        val.money = val.couponFee;
      } else {
        // 折扣需要计算
        let money = (this.money * 1 - this.money * (val.rebate / 10)).toFixed(
          2
        );
        // 折扣抵扣 最高可抵扣金额
        val.money =
          parseFloat(money) > val.upFee ? val.upFee : parseFloat(money);
      }
      uni.setStorageSync("change_coupon", val);
      uni.navigateBack({
        delta: -1,
      });
    },
    async get_coupon() {
      const { code, body } = await my_coupon(this.query);
      if (code === "0") {
        let records = body.records || [];
        // 筛选条件适合的数据
        this.getTheBest(this.goods, records);
      }
    },
    getTheBest(goods, tickets) {
      console.log("【开始匹配优惠券--------------------】", goods, tickets);
      if (!tickets.length) return uni.setStorageSync("change_coupon", {});
      //筛选出当前商品列表内可用优惠券
      const allCanUseList = tickets.filter(
        (v) =>
          goods.some((it) => v.goodsRelIdList.includes(it.id)) || !v.goodsRel
      );
      if (!allCanUseList.length) return uni.setStorageSync("change_coupon", {});
      //匹配出所有优惠券对应的商品
      const goodsGroup = allCanUseList.reduce((pre, cur) => {
        //当前优惠券的可用商品
        let goodsItems = goods.filter((v) => cur.goodsRelIdList.includes(v.id));
        if (!cur.goodsRel) {
          //通用卷的情况
          goodsItems = goods;
        }
        pre.push({
          ticket: cur, //优惠券
          goodsValues: goodsItems, //商品s
          totalPrice: goodsItems.reduce((p, c) => {
            //计算商品总价
            p += c.price * c.number;
            return p;
          }, 0),
        });
        return pre;
      }, []);
      //二次筛选，得到所有可用优惠券，满级需要判断，折扣直接添加 1满减 2折扣
      const filterGoodsGroup = goodsGroup.reduce((pre, cur) => {
        //商品金额为0时候不需要优惠券
        if (cur.totalPrice == 0) {
          return pre;
        }
        //折扣
        if (cur.ticket.type != 1) {
          pre.push(cur);
          return pre;
        }
        //满减 总金额需要大于启用金额
        if (cur.totalPrice >= cur.ticket.enableFee) {
          pre.push(cur);
        }
        return pre;
      }, []);
      //计算所有优惠券的优惠金额，
      filterGoodsGroup.forEach((v) => {
        //满减直接赋值
        if (v.ticket.type == 1) {
          v.subtractNum = v.ticket.couponFee;
        } else {
          //折扣计算
          let num = (
            v.totalPrice * 1 -
            v.totalPrice * (v.ticket.rebate / 10)
          ).toFixed(2);
          //超过最大优惠取最大优惠
          v.subtractNum =
            parseFloat(num) > v.ticket.upFee ? v.ticket.upFee : parseFloat(num);
        }
      });
      //赋值可选优惠券列表
      this.coupon_list = filterGoodsGroup.map((v) => {
        return {
          ...v.ticket,
          money: v.subtractNum,
        };
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.ty-nav-li {
  border-radius: 32rpx;
  &.bg-f8ff {
    border-radius: 32rpx 32rpx 0 0;
    .t-b {
      color: #000000;
    }
  }
}
.ty-use {
  border-radius: 0 80rpx 0 0;
}
.ty-used {
  border-radius: 80rpx 80rpx 0 0;
}
.ty-invalid {
  border-radius: 80rpx 0 0 0;
}

.scroll-view_H {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 9;
}
.ty-circle-box {
  border-radius: 0 34rpx 34rpx 0;
}
.show-in-top {
  // box-shadow: 1rpx 0px 1rpx rgba(0,102,29,0.15) inset;
  transform: rotate(90deg);
  border-radius: 50% 0 0 50%;
}
.show-in-bottom {
  // box-shadow: 1rpx 0px 1rpx rgba(0,102,29,0.15) inset;
  transform: rotate(-90deg);
  border-radius: 50% 0 0 50%;
}
</style>
